// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: daniel

#include "coin2/exchange/gopax/api_order/native_private_client.h"

#include "coin2/exchange/base/api_util/url_params_builder.h"
#include "coin2/exchange/base/order/order.h"
#include "coin2/exchange/gopax/api_util/auth_key.h"
#include "coin2/exchange/gopax/symbology/product.h"
#include "coin2/exchange/order/gopax.pb.h"

constexpr auto EXAMPLE_SPOT_COINONE = R"(
"connection_config": {
  "key_filepath": "/home/ec2-user/config/trade/xunke06/gopax/trade_key.json",
  "rate_limit_info": {
    "spot_gopax": {
      "req_all": {
        "secs": 1,
        "reqs": 10
      }
    }
  }
})";

GopaxNativePrivateClient::GopaxNativePrivateClient(
    const MarketExchangeApi& mea,
    const NativeClientConfig& config) {
  mea_ = mea;
  NativeClientConfig cfg;
  cfg.set_rest_host("api.gopax.co.kr");
  cfg.set_rest_host_port(443);
  cfg.MergeFrom(config);
  LOG(INFO) << "[GopaxNativePrivateClient] config: " << cfg.DebugString();

  auths_.Construct<GopaxRestAuth, NativeClientConfig>(cfg);

  // rate limit tracker
  using RateConfig = coin2::exchange::base::order::RateConfig;
  coin2::exchange::order::RateLimitInfoSpotGopax rate_config;
  RateConfig::Get()->GetConfig(mea_, config, &rate_config);
  if (!rate_config.has_req_all()) {
    RateConfig::CheckFail(mea_.String(), EXAMPLE_SPOT_COINONE);
  }
  const auto& req_all = rate_config.req_all();
  LOG(INFO) << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
            << "\nOG request rate was set as below:\n"
            << "\nreq_all: [" << req_all.reqs() << " (reqs) / " << req_all.secs() << " (seconds)]"
            << "\n\nOr you can configure customized rate in driver config. For example: "
            << EXAMPLE_SPOT_COINONE
            << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
  rate_tracker_ = std::make_unique<Base::RateTracker>(req_all.secs() * 1'000'000'000LL);
  rate_tracker_->SetRateLimitInfo(req_all.reqs(), req_all.reqs());
  rate_tracker_->SetRateLimitInfoString(&rate_config);
}

auto GopaxNativePrivateClient::QueryAccountBalance(const RestParams& params) -> HttpContextPtr {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::QUERY)) {
    LOG(ERROR) << "[QueryBalance] failed, rate limit hit!";
    return {};
  }
  auto endpoint = path_query_account_balance_;
  UrlParamsBuilder builder;
  if (params.has_asset()) {
    endpoint += "/" + params.asset();
  }
  auto context = GetAuth()->CreateRequestByGetWithSignature(endpoint, &builder);
  Push(1, ts, ActionType::QUERY);

  context->query_type = OrderSubTopicId::REST_ACCOUNT_BALANCE;
  return HttpContextPtr(context);
}

auto GopaxNativePrivateClient::QueryAllOrders(const RestParams& params) -> HttpContextPtr {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::QUERY)) {
    LOG(ERROR) << "[QueryAllOrders] failed, rate limit hit!";
    return {};
  }
  UrlParamsBuilder builder;
  builder.PutGet("includePast", "true");
  builder.PutGet("pagination", params.pagination());
  auto context = GetAuth()->CreateRequestByGetWithSignature(path_query_all_orders_, &builder);
  Push(1, ts, ActionType::QUERY);

  context->query_type = OrderSubTopicId::REST_ALL_ORDERS;
  return HttpContextPtr(context);
}

auto GopaxNativePrivateClient::QueryTrades(const RestParams& params) -> HttpContextPtr {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::QUERY)) {
    LOG(ERROR) << "[QueryTrades] failed, rate limit hit!";
    return {};
  }
  UrlParamsBuilder builder;
  if (params.has_pair()) {
    builder.PutGet("tradingPairName", params.pair());
  }
  auto context = GetAuth()->CreateRequestByGetWithSignature(path_query_trades_, &builder);
  Push(1, ts, ActionType::QUERY);

  context->query_type = OrderSubTopicId::REST_FILL_ORDERS;
  return HttpContextPtr(context);
}

auto GopaxNativePrivateClient::QueryTransfer(const RestParams& params) -> HttpContextPtr {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::QUERY)) {
    LOG(ERROR) << "[QueryTransfer] failed, rate limit hit!";
    return {};
  }
  UrlParamsBuilder builder;
  auto context = GetAuth()->CreateRequestByGetWithSignature(path_query_transfer_, &builder);
  Push(1, ts, ActionType::QUERY);

  context->query_type = OrderSubTopicId::TRANSFER;
  return HttpContextPtr(context);
}

auto GopaxNativePrivateClient::PlaceOrder(const RestParams& params) -> HttpContextPtr {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::PLACE)) {
    LOG(ERROR) << "[PlaceOrder] failed, rate limit hit!";
    return {};
  }
  UrlParamsBuilder builder;
  builder.PutPost("clientOrderId", params.client_order_id());
  builder.PutPost("tradingPairName", params.pair());
  builder.PutPost("side", params.side());
  builder.PutPost("type", params.type());
  builder.PutPost("price", params.price());
  builder.PutPost("amount", params.qty());
  // builder.PutPost("protection", params.protection());
  builder.PutPost("timeInForce", params.time_in_force());
  auto context = GetAuth()->CreateRequestByPostWithSignature(path_place_order_, &builder);
  Push(1, ts, ActionType::PLACE);

  context->query_type = OrderSubTopicId::SUBMIT_RESPONSE;
  return HttpContextPtr(context);
}

auto GopaxNativePrivateClient::CancelOrder(const RestParams& params) -> HttpContextPtr {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::CANCEL)) {
    LOG(ERROR) << "[CancelOrder] failed, rate limit hit!";
    return {};
  }
  UrlParamsBuilder builder;
  auto endpoint = path_cancel_order_;
  if (params.has_order_id()) {
    endpoint += "/" + params.order_id();
  } else if (params.has_client_order_id()) {
    endpoint += "/clientOrderId/" + params.client_order_id();
  } else {
    LOG(ERROR) << "[CancelOrder] failed, order_id/client_order_id is needed";
    return {};
  }
  auto context = GetAuth()->CreateRequestByDeleteWithSignature(endpoint, &builder);
  Push(1, ts, ActionType::CANCEL);

  context->query_type = OrderSubTopicId::CANCEL_RESPONSE;
  return HttpContextPtr(context);
}

auto GopaxNativePrivateClient::PlaceOrderNorm(const OrderExecution& order_exe) -> HttpContextPtr {
  const auto& order_spec = *order_exe.order_spec;
  const auto proc_order_id = order_exe.proc_order_id;
  auto params = GetRestOrderParams(order_spec, proc_order_id);
  return PlaceOrder(params);
}

auto GopaxNativePrivateClient::CancelOrderNorm(const OrderExecution& order_exe) -> HttpContextPtr {
  auto params = GetRestCancelParams(*order_exe.oc);
  return CancelOrder(params);
}

auto GopaxNativePrivateClient::GetRestOrderParams(
    const OrderSpec& order_spec,
    int64_t proc_order_id) -> RestParams {
  RestParams params;

  using coin2::exchange::gopax::symbology::GopaxProduct;
  auto product = GopaxProduct::FromStr(order_spec.product, order_spec.order_created_time);
  auto product_holder = GetProductHolder(product, order_spec.order_created_time);
  auto formatter = product_holder->product_info().order_formatter();
  params.set_client_order_id(std::to_string(proc_order_id));
  params.set_pair(order_spec.product);
  params.set_qty(formatter.FormatQty(order_spec.qty));
  if (order_spec.order_type == OrderType::LIMIT_ORDER) {
    params.set_price(formatter.FormatPrice(order_spec.price));
    params.set_type("limit");
  } else if (order_spec.order_type == OrderType::MARKET_ORDER) {
    params.set_type("market");
  } else {
    NOTREACHED() << "unsupported order type: " << static_cast<int>(order_spec.order_type);
  }

  if (order_spec.order_side == OrderSide::BUY_ORDER) {
    params.set_side("buy");
  } else if (order_spec.order_side == OrderSide::SELL_ORDER) {
    params.set_side("sell");
  } else {
    NOTREACHED() << "Unknown order side: " << static_cast<int>(order_spec.order_side);
  }

  switch (order_spec.duration) {
    case coin::proto::OrderDuration::GTC_ORDER:
      params.set_time_in_force("gtc");
      break;
    case coin::proto::OrderDuration::IOC_ORDER:
      params.set_time_in_force("ioc");
      break;
    case coin::proto::OrderDuration::FOK_ORDER:
      params.set_time_in_force("fok");
      break;
    default:
      break;
  }
  if (order_spec.post_only) {
    params.set_time_in_force("po");
  }

  return params;
}

auto GopaxNativePrivateClient::GetRestCancelParams(const IOrderContext& order_context)
    -> RestParams {
  RestParams params;
  params.set_order_id(order_context.exchange_order_id());

  return params;
}

std::shared_ptr<AsioHttpContext> GopaxNativePrivateClient::SubmitOrderExecution(
    const OrderExecutionProto& order) {
  switch (order.type()) {
    case OrderExecutionProto::SUBMIT_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params = GetRestOrderParams(*order_spec, order.proc_order_id());
      return PlaceOrder(params);
    }
    case OrderExecutionProto::CANCEL_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params = GetRestOrderParams(*order_spec, order.proc_order_id());
      return CancelOrder(params);
    }
    default: {
      return nullptr;
    }
  }
}

std::shared_ptr<AsioHttpContext> GopaxNativePrivateClient::SubmitRestQuery(
    const RestQueryProto& query) {
  RestParams params;
  switch (query.type()) {
    case RestQueryProto::QUERY_ACCOUNT_BALANCE: {
      return QueryAccountBalance(params);
    }
    case RestQueryProto::QUERY_OPEN_ORDERS: {
      return QueryAllOrders(params);
    }
    default: {
      return nullptr;
    }
  }
}
